package com.durian.finance.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.durian.common.core.domain.R;
import com.durian.common.core.web.domain.AjaxResult;
import com.durian.finance.domain.GenConstructVO;
import com.durian.finance.utils.Doc2Pdf;
import com.durian.system.api.RemoteFileService;
import com.durian.system.api.domain.SysFile;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhouzhiyi
 * @Date 2022/6/29 22:36
 * @Description 生成合同
 */
@RestController
@RequestMapping("/genConstruct")
public class GenConstruct {

    @Resource
    private RemoteFileService remoteFileService;



    /**
     * 生成Word文档 并 转换PDF
     *
     * @param info 合同信息
     */
    @GetMapping("/gen")
    public AjaxResult gen(GenConstructVO info) throws Exception {

        // 设置当前时间，承租年份
        info.setNowTime(new Date()).setTermYear(DateUtil.betweenYear(info.getBeginTime(),info.getEndTime(),false));

        //创建配置对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置默认生成文件编码
        configuration.setDefaultEncoding("utf-8");
        //设置模板路径
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");
        //获取模板
        Template template = configuration.getTemplate("construct.ftl");

        //加载数据========================================
        Map<String, Object> infoMap = BeanUtil.beanToMap(info);

        //========================================
        //创建输出对象,将文件输出到D盘根目录下
        FileWriter fileWriter = new FileWriter("E:/upload/index.doc");
        //渲染模板和数据
        template.process(infoMap, fileWriter);
        //关闭输出
        fileWriter.close();

        // 转PDF
        // 生成唯一名称
        String fileName = IdUtil.simpleUUID().concat(".pdf");
        Doc2Pdf.doc2pdf("E:/upload/index.doc","E:/upload/".concat(fileName));

        return AjaxResult.success("合同生成成功","http://localhost:8081/upload/".concat(fileName));

        /*
            上传到minio
         */
//        File file = new File("E:/upload/",fileName);
//        FileItem fileItem = this.getMultipartFile(file,fileName);
//        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
//        R<SysFile> upload = remoteFileService.upload(multipartFile);
//        return AjaxResult.success("合同生成成功",upload);
    }

    /**
     * 上传身份证获取信息
     *
     * @param file 身份证图片
     */
    @PostMapping("/idCardMsg")
    public AjaxResult getIdCardMsg(MultipartFile file) throws IOException {

        R<SysFile> upload = remoteFileService.upload(file);
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("api_key","RyITCWi1sSNtiy_vo9NHVTu5ASG0AZAA");
        msgMap.put("api_secret","7AEY1NCIZFaeR-17MF1PT_B-B5o_4xns");

        String filePath = upload.getData().getUrl().replace("http://127.0.0.1:9301/", "E:/");
        msgMap.put("image_file", FileUtil.file(filePath));

        String post = HttpUtil.post("https://api-cn.faceplusplus.com/cardpp/v1/ocridcard", msgMap);

        AjaxResult success = AjaxResult.success();
        success.put("upload",upload.getData());
        success.put("idMsg", JSON.parseObject(post));
        return success;
    }


    /**
     * 将本地文件转换为 MultipartFile对象
     *
     * @param file 文件路径
     * @param fieldName 文件名称
     * @return FileItem
     */
    private FileItem getMultipartFile(File file, String fieldName) {

        /*
            构造该类的一个预配置实例
            形参:
                sizeThreshold——以字节为单位的阈值，低于该阈值的项将保留在内存中，高于该阈值的项将作为文件存储。
                repository—数据存储库，如果条目大小超过阈值，将在其中创建文件。
         */
        FileItemFactory factory = new DiskFileItemFactory(16, null);

        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        int len = 8192;
        byte[] buffer = new byte[len];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }


}
